﻿using Zhp.Common.Helper;
using Zhp.Common.WebApp;
using Zhp.Entity.Chat;
using Zhp.Entity.Sys;
using Zhp.Entity.SysEnum;
using Zhp.IService.Chat;
using Zhp.IService.Common;
using Zhp.Model.Chat;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Chat
{
    public class ChatFriendService : BaseService<ChatFriend>, IChatFriendService
    {
        IBaseRepository<SysUser> _sysUserRep;
        IFileService _fileService;
        public ChatFriendService(ICurrentUser currentUser, IBaseRepository<ChatFriend> rep, IBaseRepository<SysUser> sysUserRep, IFileService fileService)
        {
            _currentUser = currentUser;
            _rep = rep;
            _sysUserRep = sysUserRep;
            _fileService = fileService;
        }

        public async Task<List<ChatFriendModel>> GetChatFriendList()
        {
            var friendList = await _rep.GetListAsync(x => x.UserId == _currentUser.UserId);
            var userList = await _sysUserRep.AsQueryable().Where(x => x.Id != _currentUser.UserId).Select(x => new ChatFriendModel { FriendUserId = x.Id, NickName = x.NickName }).ToListAsync();
            foreach (var item in userList)
            {
                item.FriendAvatar = await _fileService.GetBase64ImageString(FileEnum.Avatar, item.FriendUserId);
                var friend = friendList.FirstOrDefault(x => x.FriendUserId == item.FriendUserId);
                if (friend != null)
                {
                    item.FriendId = friend.Id;
                    item.NickName = friend.FriendNickName;
                    item.PairID = friend.PairID;
                    item.IsFriend = true;
                }
            }

            return userList;
        }

        public async Task<bool> Create(AddChatFriendModel friend)
        {
            var pairID = SnowFlakeHelper.GetLongId();

            //加好友
            var user = new ChatFriend
            {
                Id = SnowFlakeHelper.GetLongId(),
                UserId = _currentUser.UserId,
                FriendUserId = friend.FriendUserId,
                FriendNickName = friend.NickName,
                PairID = pairID,
            };

            var friendUser = new ChatFriend
            {
                Id = SnowFlakeHelper.GetLongId(),
                UserId = friend.FriendUserId,
                FriendUserId = _currentUser.UserId,
                FriendNickName = _currentUser.NickName,
                PairID = pairID,
            };

            user.InsertExtraEntity.Add(friendUser);

            return await user.InsertAsync();
        }
    }
}
